package com.sailfish.springbootdemo.service.db1;

import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db1.*;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.*;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class PcbaWorkshopServiceImpl implements PcbaWorkshopService {

    @Autowired
    private PcbaWorkshopDao pcbaWorkshopDao;

    @Autowired
    private PcbaCompanyDao pcbaCompanyDao;

    @Autowired
    private PcbaProcessDao pcbaProcessDao;

    @Autowired
    private PcbaDeviceResourceDao pcbaDeviceResourceDao;

    @Autowired
    private PcbaSpecialResourceDao pcbaSpecialResourceDao;

    @Autowired
    private PcbaDeviceTypeDao pcbaDeviceTypeDao;

    @Autowired
    private CommonJudgeCanDeleteService commonService;

    @Qualifier("MysqlTransactionManager1")
    @Autowired
    private DataSourceTransactionManager transactionManager1;

    @Autowired
    private OperateService operateService;

    private String operateSmallType = "车间管理";

    @Override
    public List<PcbaWorkshop> getAllPcbaWorkshopByCompanyId(String searchValue, Integer pcbaCompanyId) {
        List<PcbaWorkshop> list = pcbaWorkshopDao.getAllPcbaWorkshopByCompanyId(searchValue, pcbaCompanyId);
        for (PcbaWorkshop pcbaWorkshop : list) {
            PcbaCompany pcbaCompanyById = pcbaCompanyDao.getPcbaCompanyById(pcbaWorkshop.getPcbaCompanyId());
            pcbaWorkshop.setPcbaCompany(pcbaCompanyById);
        }
        return list;
    }

    @Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result deleteWorkshop(Integer pcbaWorkshopId) {
        try {
            if (pcbaWorkshopId == null || "".equals(pcbaWorkshopId.toString())) {
                return ResultUtil.error(500, "缺少参数pcbaWorkshopId", "Miss Param pcbaWorkshopId", null);
            }

            Map<String, Integer> stringIntegerMap = commonService.judgeCanDeletePcbaWorkshop(pcbaWorkshopId);
            if (stringIntegerMap.get("pcbaLineNum") > 0) {
                return ResultUtil.error(500,
                        "禁止删除，当前项" + stringIntegerMap.get("pcbaLineNum") + "处关联线体"
                        ,
                        "Forbidden Delete", null);
            }

            String userId = UserHeaderHolder.getUserId();
            PcbaWorkshop oldPcbaWorkshop = pcbaWorkshopDao.getPcbaWorkshopById(pcbaWorkshopId);

            Integer integer = pcbaWorkshopDao.deleteWorkshop(pcbaWorkshopId);
            if (integer > 0) {

                // 删除特殊工艺
                pcbaSpecialResourceDao.deleteByWorkshopId(pcbaWorkshopId);

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 2, 1, new Date(), JSONObject.toJSONString(oldPcbaWorkshop), null));

                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result addOrUpdatePcbaWorkshop(String mode, PcbaWorkshop pcbaWorkshop) {
        try {
            if (pcbaWorkshop == null) {
                return ResultUtil.error(500, "缺少参数pcbaWorkshop", "Miss Param pcbaWorkshop", null);
            }
            if (mode == null || "".equals(mode)) {
                return ResultUtil.error(500, "缺少参数mode", "Miss Param mode", null);
            }
            if (!("edit".equals(mode) || "add".equals(mode))) {
                return ResultUtil.error(500, "mode 参数错误", "mode Param Error", null);
            }

            String userId = UserHeaderHolder.getUserId();

            if ("edit".equals(mode)) {
                if (pcbaWorkshop.getPcbaWorkshopId() == null || "".equals(pcbaWorkshop.getPcbaWorkshopId().toString())) {
                    return ResultUtil.error(500, "缺少参数pcbaWorkshopId", "Miss Param pcbaWorkshopId", null);
                }

                List<PcbaCompany> pcbaCompanies = pcbaWorkshopDao.judgeUniquePcbaWorkshop(pcbaWorkshop.getPcbaCompanyId(), pcbaWorkshop.getPcbaWorkshopId(), pcbaWorkshop.getPcbaWorkshopNameCn());
                if (pcbaCompanies.size() > 0) {
                    return ResultUtil.error(500, "修改失败，存在相同名字", "Operate Fail", null);
                }

                PcbaWorkshop oldPcbaWorkshop = pcbaWorkshopDao.getPcbaWorkshopById(pcbaWorkshop.getPcbaWorkshopId());

                pcbaWorkshop.setUpdateTime(new Date());
                Integer integer = pcbaWorkshopDao.updatePcbaWorkshop(pcbaWorkshop);
                if (integer > 0) {

                    // 操作日志
                    operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldPcbaWorkshop), JSONObject.toJSONString(pcbaWorkshop)));

                    return ResultUtil.success(null);
                }
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            } else {

                List<PcbaWorkshop> allPcbaWorkshopByCompanyId = pcbaWorkshopDao.getWorkshopByCompanyIdAndName(pcbaWorkshop.getPcbaWorkshopNameCn(), pcbaWorkshop.getPcbaCompanyId());
                if (allPcbaWorkshopByCompanyId.size() > 0) {
                    return ResultUtil.error(500, "该工厂下已存在此车间", "Already Exist", null);
                }

                Date d = new Date();
                pcbaWorkshop.setCreateTime(d);
                Integer integer = pcbaWorkshopDao.addPcbaWorkshop(pcbaWorkshop);
                if (integer > 0) {

                    // 操作日志
                    operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, new Date(), null, JSONObject.toJSONString(pcbaWorkshop)));

                    // 判断该车间下其他工艺是否有，没有的话需要新增
                    List<PcbaDeviceType> techOwnPcbaDeviceTypeList = pcbaDeviceTypeDao.getAllPcbaDeviceType(null, 1);
                    List<PcbaSpecialResource> addPcbaSpecialResourceList = new ArrayList<>();
                    if (techOwnPcbaDeviceTypeList.size() > 0) {
                        for (PcbaDeviceType pcbaDeviceType : techOwnPcbaDeviceTypeList) {
                            PcbaSpecialResource addPcbaSpecialResource = new PcbaSpecialResource();
                            addPcbaSpecialResource.setStatus(4);
                            addPcbaSpecialResource.setCreateTime(d);
                            addPcbaSpecialResource.setSort(100);
                            addPcbaSpecialResource.setPcbaCompanyId(pcbaWorkshop.getPcbaCompanyId());
                            addPcbaSpecialResource.setPcbaWorkshopId(pcbaWorkshop.getPcbaWorkshopId());
                            addPcbaSpecialResource.setPcbaDeviceTypeId(pcbaDeviceType.getPcbaDeviceTypeId());
                            pcbaSpecialResourceDao.addPcbaSpecialResource(addPcbaSpecialResource);
                            addPcbaSpecialResourceList.add(addPcbaSpecialResource);
                        }
                    }
                    // 操作日志
                    operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, new Date(), null, JSONObject.toJSONString(addPcbaSpecialResourceList)));
                    return ResultUtil.success(null);
                }
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
}
